package com.ysstech.common.util;


import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 此工具类包含的主要功能有：
 * 1.userId隐式传输，保证数据安全；
 * 2.不对称加密方式，防止数据篡改；
 */
@Slf4j
public class TokenUtil {  //设置过期时间
    private static final long EXPIRE_DATE = 60 * 60 * 100000;
    //token秘钥
    private static final String TOKEN_SECRET = "YSS";

    public static String token(String UserId) throws Exception {
        log.info(UserId + "获取token！");
        String token = "";
        try {
            if (StringUtils.isBlank(UserId)) {
                return null;
            }
            //过期时间
            Date date = new Date(System.currentTimeMillis() + EXPIRE_DATE);
            //秘钥及加密算法
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            //设置头部信息
            Map<String, Object> header = new HashMap<>();
            header.put("typ", "JWT");
            header.put("alg", "HS256");
            //携带username，password信息，生成签名
            token = JWT.create()
                    .withHeader(header)
                    .withClaim("UserId", UserId)
                    .withExpiresAt(date)
                    .sign(algorithm);
            log.info(UserId + "获取token值为：" + token);
        } catch (Exception e) {
            log.error(e.toString());
            throw new Exception("获取token值失败！");
        }
        return token;
    }

    /**
     * @desc 验证token，通过返回true
     * @params [token]需要校验的串
     **/
    public static boolean verify(String token) throws Exception{
        try {
            if (StringUtils.isBlank(token)) {
                return false;
            }
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            if (null != jwt && StringUtils.isNotBlank(jwt.getToken())) {
                return true;
            }
        } catch (Exception e) {
            log.error(e.toString());
            throw new Exception("验证token值失败！");
        }
        return false;
    }


    /**
     * @desc 验证token，通过返回true
     * @params [token]需要校验的串
     **/
    public static String getKey(String token)throws Exception {
        try {
            if (StringUtils.isBlank(token)) {
                return null;
            }
            Algorithm algorithm = Algorithm.HMAC256(TOKEN_SECRET);
            JWTVerifier verifier = JWT.require(algorithm).build();
            DecodedJWT jwt = verifier.verify(token);
            if (null != jwt && StringUtils.isNotBlank(jwt.getToken())) {
                return jwt.getClaim("UserId").asString();
            }
        } catch (Exception e) {
            log.error(e.toString());
            throw new Exception("验证token值失败！");
        }
        return null;
    }

}
